<?php
namespace app\admin\controller;

use think\Controller;
use app\admin\model\Config as Configs;

class Config extends Common
{
    private $cModel;   //当前控制器关联模型
    
    public function _initialize()
    {
        parent::_initialize();
        $this->cModel = new Configs;   //别名：避免与控制名冲突
    }

    //全局配置
    public function index()
    {
        if (request()->isPost()){
            $postData = input('post.');
            foreach ($postData as $key=>$val){
                if($this->cModel->where('k',$key)->find()){
                    //更新
                    $result = $this->cModel->where('k',$key)->update(['v'=>$val,'update_time'=>time()]);
                }else{
                    //插入
                    $insertData = [
                        'k'=>$key,
                        'v'=>$val,
                        'create_time'=>time()
                    ];
                    $result = $this->cModel->insert($insertData);
                }
            }
            return ajaxReturn(lang('action_success'), url('index'));
        }else{
            $rData = $this->cModel->select();
            $data = [];
            foreach ($rData as $key=>$val){
                $data[$val['k']] = $val['v'];
            }
            $this->assign('data', $data);
            return $this->fetch();
        }
    }
    //扩展配置
    public function extend()
    {
        if (request()->isPost()){
            $postData = input('post.');
            foreach ($postData as $key=>$val){
                if($this->cModel->where('k',$key)->find()){
                    //更新
                    $result = $this->cModel->where('k',$key)->update(['v'=>$val,'update_time'=>time()]);
                }else{
                    //插入
                    $insertData = [
                        'k'=>$key,
                        'v'=>$val,
                        'create_time'=>time()
                    ];
                    $result = $this->cModel->insert($insertData);
                }
            }
            return ajaxReturn(lang('action_success'), url('extend'));
        }else{
            $rData = $this->cModel->select();
            $data = [];
            foreach ($rData as $key=>$val){
                $data[$val['k']] = $val['v'];
            }
            $this->assign('data', $data);
            return $this->fetch();
        }
    }
}